package vn.com.vega.music.utils;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.player.IMediaPlaybackService;
import vn.com.vega.chacha.v2.player.PlayerService;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.device.FileStorage;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.view.custom.ChaChaDialog;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;


public class Util {

	private Context mContext;

	public Util(Context context) {
		mContext = context;
	}

	@SuppressLint("NewApi")
	public void setSharedPre(String name, String value) {

		SharedPreferences mSharedRefs = mContext.getSharedPreferences(name,
				Activity.MODE_PRIVATE);
		Editor editor = mSharedRefs.edit();
		editor.putString(name, value);

		// if (Build.VERSION.SDK_INT >= 9) {
		// editor.apply();
		// } else {
		editor.commit();
		// }

	}

	public String getSharedPre(String name) {

		SharedPreferences mSharedRefs = null;
		mSharedRefs = mContext
				.getSharedPreferences(name, Activity.MODE_PRIVATE);

		return mSharedRefs.getString(name, "");

	}
	
	public static int getPriceFromString(String price) {
		StringBuilder priceNumber = new StringBuilder();
		for (int i = 0; i < price.length(); i++) {
			Character c = price.charAt(i);
			if (Character.isDigit(c)) {
				priceNumber.append(c);
			} else {
				break;
			}
		}
		return Integer.valueOf(priceNumber.toString()).intValue();
	}

	public static String intToStringTimeFormat(int time) {
		String strTemp = new String();
		int minutes = time / 60;
		int seconds = time % 60;

		if (minutes < 10)
			strTemp = "0" + Integer.toString(minutes) + ":";
		else
			strTemp = Integer.toString(minutes) + ":";

		if (seconds < 10)
			strTemp = strTemp + "0" + Integer.toString(seconds);
		else
			strTemp = strTemp + Integer.toString(seconds);

		return strTemp;
	}

	public static boolean checkStringIsemptyOrNull(String str) {
		if (str == null) {
			return true;
		}
		if (str.trim().equalsIgnoreCase("")) {
			return true;
		}
		return false;
	}

	public static void showAlert(Context ctx, String mess) {
		ChaChaDialog dialog = new ChaChaDialog(ctx, null);
		dialog.setTitle(ctx.getText(R.string.dialog_notification));
		dialog.setMessage(mess);
		dialog.addDefaultOkBtn("Đóng");
		dialog.show();
	}

	public static void goToHome(Context ctx) {
		Intent homeIntent = new Intent(Intent.ACTION_MAIN);
		homeIntent.addCategory(Intent.CATEGORY_HOME);
		homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		ctx.startActivity(homeIntent);
	}

	public static IMediaPlaybackService sService = null;

	private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>();

	public static class ServiceToken {
		ContextWrapper mWrappedContext;

		ServiceToken(ContextWrapper context) {
			mWrappedContext = context;
		}
	}

	public static ServiceToken bindToService(Activity context) {
		return bindToService(context, null);
	}

	public static ServiceToken bindToService(Activity context,
			ServiceConnection callback) {
		Activity realActivity = context.getParent();
		if (realActivity == null) {
			realActivity = context;
		}
		ContextWrapper cw = new ContextWrapper(realActivity);
		cw.startService(new Intent(cw, PlayerService.class));
		ServiceBinder sb = new ServiceBinder(callback);
		if (cw.bindService((new Intent()).setClass(cw, PlayerService.class),
				sb, 0)) {
			sConnectionMap.put(cw, sb);
			return new ServiceToken(cw);
		}
		Log.e("Music", "Failed to bind to service");
		return null;
	}

	public static void unbindFromService(ServiceToken token) {
		if (token == null) {
			Log.e("MusicUtils", "Trying to unbind with null token");
			return;
		}
		ContextWrapper cw = token.mWrappedContext;
		ServiceBinder sb = sConnectionMap.remove(cw);
		if (sb == null) {
			Log.e("MusicUtils", "Trying to unbind for unknown Context");
			return;
		}
		cw.unbindService(sb);
		if (sConnectionMap.isEmpty()) {
			// presumably there is nobody interested in the service at this
			// point,
			// so don't hang on to the ServiceConnection
			sService = null;
		}
	}

	private static class ServiceBinder implements ServiceConnection {
		ServiceConnection mCallback;

		ServiceBinder(ServiceConnection callback) {
			mCallback = callback;
		}

		public void onServiceConnected(ComponentName className,
				android.os.IBinder service) {
			// Log.e(TAG, "before set sService");
			sService = IMediaPlaybackService.Stub.asInterface(service);
			if (mCallback != null) {
				mCallback.onServiceConnected(className, service);
			}
		}

		public void onServiceDisconnected(ComponentName className) {
			if (mCallback != null) {
				mCallback.onServiceDisconnected(className);
			}
			sService = null;
		}
	}

	// ------------ Util for play song ------------------------------//

	// public static void SelectSongPlay()

	public static void openListSong(final List<Song> listSong,
			final int position, Activity act) {
		if (sService == null) {
			ServiceConnection connection = new ServiceConnection() {

				@Override
				public void onServiceDisconnected(ComponentName name) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onServiceConnected(ComponentName name,
						IBinder service) {
					// TODO Auto-generated method stub
					openListSong(listSong, position);

				}

			};
			bindToService(act, connection);
		} else {
			openListSong(listSong, position);
		}
	}

	private static void openListSong(List<Song> listSong, int position) {
		if (sService != null) {
			try {
				sService.openList(listSong, position);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			// try to play music with service had stoped
		}
	}

	public static Song getCurrentSongPlay() {
		if (sService != null) {
			try {
				return sService.getCurrentSong();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static int getCurrentTime() {
		if (sService != null) {
			try {
				return (int) (sService.getPosition() / 1000);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return 0;
	}

	public static int getTotalTime() {
		if (sService != null) {
			try {
				return (int) (sService.getDuration() / 1000);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return 0;
	}

	public static int getRepeateMode() {
		return PlayerService.REPEAT_NONE;
	}

	public static int getShufferMode() {
		return PlayerService.SHUFFLE_OFF;
	}

	public static boolean isPlaying() {
		if (sService == null) {
			return false;
		}
		try {
			return sService.isPlaying();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public static boolean playerIsInit() {
		if (sService != null) {
			try {
				return sService.playerIsInit();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public static void next() {
		// TODO Auto-generated method stub
		if (sService != null) {
			try {
				sService.next();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void back() {
		if (sService != null) {
			try {
				sService.prev();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void pause() {
		// TODO Auto-generated method stub
		if (sService != null) {
			try {
				sService.pause();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void play() {
		if (sService != null) {
			try {
				sService.play();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void stop() {
		if (sService != null) {
			try {
				sService.stop();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public static void seek(int time) {
		if (sService != null) {
			try {
				sService.seek(time * 1000);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static List<Song> getListSongPlay() {
		if (sService != null) {
			try {
				return sService.getCurrentListPlay();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static void setShuffleMode(int shuffleMode) {
		if (sService != null) {
			try {
				sService.setShufferMode(shuffleMode);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	public static void setRepeateMode(int setRepeateMode) {
		if (sService != null) {
			try {
				sService.setRepeateMode(setRepeateMode);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public static void openSongAtPosition(int position) {
		if (sService != null) {
			try {
				sService.openSongAt(position);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static int getIndexCurrentSongPlay() {
		if (sService != null) {
			try {
				return sService.getIndexCurrentSong();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public static void share(String message, Context ctx) {
		Intent i = new Intent(android.content.Intent.ACTION_SEND);
		i.setType("text/plain");
		i.putExtra(Intent.EXTRA_TEXT, message);
		ctx.startActivity(Intent.createChooser(i, "Chia sẻ bằng"));
	}

	public static boolean insertSongToNowPlaying(final Song song, Activity act) {
		if (sService == null) {
			ServiceConnection connection = new ServiceConnection() {

				@Override
				public void onServiceDisconnected(ComponentName name) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onServiceConnected(ComponentName name,
						IBinder service) {
					// TODO Auto-generated method stub
					List<Song> listSong = new ArrayList<Song>();
					listSong.add(song);
				}

			};
			bindToService(act, connection);
		} else {
			return insertSongToNowPlaying(song);
		}
		return true;
	}

	public static boolean insertListSongToNowPlaying(final List<Song> songs,
			Activity act) {
		if (sService == null) {
			ServiceConnection connection = new ServiceConnection() {

				@Override
				public void onServiceDisconnected(ComponentName name) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onServiceConnected(ComponentName name,
						IBinder service) {
					// TODO Auto-generated method stub
					insertListSongToNowPlaying(songs);
				}

			};
			bindToService(act, connection);
		} else {
			return insertListSongToNowPlaying(songs);
		}
		return true;
	}

	private static boolean insertListSongToNowPlaying(List<Song> ListSong) {
		if (sService != null) {
			try {
				return sService.insertListSongToNowPlaying(ListSong);
			} catch (Exception e) {
				// TODO: handle exception
				return false;
			}
		}
		return false;
	}

	private static boolean insertSongToNowPlaying(Song song) {
		if (sService != null) {
			try {
				return sService.insertToNowPlaying(song);
			} catch (Exception e) {
				// TODO: handle exception
				return false;
			}
		}
		return false;
	}

	public static String encodeHttpParamas(String para) {
		try {
			return URLEncoder.encode(para, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
	}

	public static void fixBackgroundRepeat(View view) {
		Drawable bg = view.getBackground();
		if (bg != null) {
			if (bg instanceof BitmapDrawable) {
				BitmapDrawable bmp = (BitmapDrawable) bg;
				bmp.mutate(); // make sure that we aren't sharing state anymore
				bmp.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			}
		}
	}

	public static boolean checkQuota(long needed) {
		DataStore dataStore = DataStore.getInstance();
		long avail = FileStorage.getAvaiableVolume();
		long used = FileStorage.getUsedSize();
		int percent = dataStore.getMemoryLimit();
		long quota = percent * (avail + used) / 100;
		long after = needed + used;

		if (after > quota) {
			return false;
		}
		return true;
	}

	public static void unbindAll() {
		try {
			Set<Context> listContext = sConnectionMap.keySet();
			for (Context ctx : listContext) {
				ServiceBinder serviceBinder = sConnectionMap.remove(ctx);
				if (serviceBinder != null) {
					ctx.unbindService(serviceBinder);
				}
			}
			sConnectionMap.clear();
			sService = null;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	// --------------------------------//
	public static Bitmap loadBitmap(String urlStr) {
		Bitmap bitmap = null;
		InputStream in = null;

		try {
			URL url = new URL(urlStr);
			HttpURLConnection httpsURLConnection = (HttpURLConnection) url
					.openConnection();
			httpsURLConnection.connect();
			in = httpsURLConnection.getInputStream();
			bitmap = BitmapFactory.decodeStream(in);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			VegaLog.e("Exeption while down load url: ", urlStr);
		} finally {
			try {
				in.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}

		return bitmap;
	}
}
